package com.apes.bi.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.bi.model.Applet;
import com.apes.bi.repository.AppletRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.PredicateBuilder;
import com.apes.framework.jpa.spec.Specifications;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("appletService")

public class AppletService extends DomainService {

    @Autowired
    AppletRepository appletRepository;



    public Applet create(SimpleRequest request){
        Applet applet = request.getO(Applet.class);
        return appletRepository.save(applet);
    }


    public Applet update(SimpleRequest request){
        Applet applet = request.getO(Applet.class);
        return appletRepository.save(applet);
    }

    public String delete(SimpleRequest request){
        Applet applet = request.getO(Applet.class);
        appletRepository.delete(applet);
        return "删除成功";
    }


    public List<Applet> findAllForAuth(SimpleRequest request){
        JSONObject json = request.getJO();

        if( json.getString("userId")  == null || json.getString("postId") == null ) throw new RuntimeException("用户编码和岗位编码不能为空");

        // 拼接权限的查询列表
        PredicateBuilder pb = Specifications.or();
        pb.eq("appletPostPermits.post.id", json.getString("postId"));
        pb.eq("appletUserPermits.user.id", json.getString("userId"));
        Sort sort = new Sort(Sort.Direction.ASC, "id");

        return appletRepository.findAll(pb.build(true), sort);
    }

}
